#!/bin/bash
bunker=/usr/local/emhttp/plugins/dynamix.file.integrity/scripts/bunker
config=/boot/config/plugins/dynamix.file.integrity

cmd=$1
method=$2
[[ -n $3 ]] && exclude="^/mnt/disk[0-9]+/$3" || exclude="''"

if [[ -z $method ]]; then
  hash=sha256
elif [[ $method == -b2 ]]; then
  hash=blake2
elif [[ $method == -b3 ]]; then
  hash=blake3
else
  hash=md5
fi

# setup named pipe and speaker per disk ($4)
# Torqu3Wr3nch: Update code to handle only file.partial moves caused by the Unraid Mover. 
pipe=/var/run/hash.pipe.$4
[[ -p $pipe ]] || mkfifo $pipe
inotifywait -dsrqo $pipe -e close_write,moved_to --exclude "$exclude" --format '%w%f' "/mnt/$4"

# listener
while read -r file; do
  if [[ -z $(getfattr -n user.$hash --only-values "$file" 2>/dev/null) ]]; then
    $bunker -${cmd}q1 $method -f "$config/saved/disks.export.$(date +%Y%m%d).$hash.new.hash" "$file" >/dev/null
  else
    $bunker -Vq1 $method -f "$config/logs/disks.export.$(date +%Y%m%d).$hash.bad.log" "$file" >/dev/null
  fi
  ((active++))
done <$pipe &

# detach
disown %%
